#include "audio.h"

//==============================================================================DATA
pthread_mutex_t audio_command_mutex;
audio_command_u audio_command;

//==============================================================================THREAD
void * audio_thread( void *arg )
{	
	printf("\nAudio Thread Start...\n");

	pthread_mutex_init( &audio_command_mutex, NULL);
	audio_command.type = C_VOID;
	
	audio_start();
	if(output.handle)
		output.open();

	//--------------------------------------------------------------------------WORKFLOW 
	while(1)
	{
		{//PRE-PROCESSING//
			bool need;
			if(output.handle)
				need = output.do_you_need_to_decode();
			if( need && !now_playback->music_buf )
				decoder_solution( now_playback );
		}

		{//EXECUTE-OPERATION//
			if(output.handle)
				output.operate( now_playback, control, &status );
		}

		{//TURN-OFF//
			control = GONE;
			switches.show_on = FALSE;
			if( status.flags & AVOID_POST_PROCESSING ) continue;
		}

		{//POST-PROCESSING//
			int i = 0;
			if( status.flags & EOS ){
				if( CUR_SEQU < CUR_LIST.total_entries_number-1 ){
					while( CUR_LIST.sequence[i] != CUR_SEQU+1 ) i++;
					CUR_LIST.cur_entry = i;
					now_playback = CUR_ENTRY;
					control = START;
					switches.show_on = TRUE;
				}else{
					control = STOP;
				} 
			}
			
			if( status.flags & ERROR ){
				perror( "\nERROR: " );
				status.flags |= EOS;
				switches.show_on = TRUE;
			}			
		}
		
		{//DETECT-SIGNAL//
			if( pthread_mutex_trylock( &audio_command_mutex ) != 0 ) goto go_on;
			switch( audio_command.type ){
				case C_VOID: 			break;
				case C_EXIT:			handle_C_EXIT(); break;	
			
				case C_PLAYBACK: 		handle_C_PLAYBACK(); break;
				case C_PAUSE: 			handle_C_PAUSE(); break;
				case C_STOP:			handle_C_STOP(); break;
				case C_VOLUME:			handle_C_VOLUME(); break;
				case C_SEEK:			handle_C_SEEK(); break;
				
				case C_LIST_ADD:		handle_C_LIST_ADD(); break;
				case C_LIST_DEL:		handle_C_LIST_DEL(); break;
				case C_LIST_CLEAR_STATUS:	handle_C_LIST_CLEAR_STATUS(); break;
				
				case C_CHANGE_OUTPUT:		handle_C_CHANGE_OUTPUT(); break;
				default : 			break;
			}
			audio_command.type = C_VOID;
			pthread_mutex_unlock( &audio_command_mutex );
go_on: 	;
		}
		
		{//SHOW//
			if( switches.show_on ){
				printf( "\nnow playback   :: %s", now_playback->name );
				printf( "\nsample rate : %d", now_playback->sample_rate );
				printf( "\nvolume      : %d", status.volume );
				printf( "\nposition    : %d\n", status.position );
			}
		}
		//fprintf(stderr, " audio " );
		usleep(100000);
	}
	//--------------------------------------------------------------------------
	
	return EXIT_SUCCESS;
}



